<template>
    <div>
        <el-button type="text" icon="el-icon-back" size="mini" @click="back">返回</el-button>
        <div class="tip">规则基本信息</div>

        <el-form ref="sopForm" :model="ruleForm" label-width="80px">
            <el-form-item label="规则名称" prop="sopName" :rules="[{ required: true, message: '请输入规则名称', trigger: 'blur' }]">
                <el-input v-model="ruleForm.sopName"></el-input>
            </el-form-item>
            <el-form-item label="企业成员">
                <el-button type="primary" @click="selectMemberVisible = true;">+ 添加成员</el-button>
                <span class="spanFont">以下企业成员的新客户触发规则后，将在侧边栏显示该规则的快捷回复。</span>
            </el-form-item>
            <el-form-item>
                <el-tag v-for="tag in ruleForm.members" :key="tag.empId" closable @close="closeTagHandle(tag)"
                        style="margin-right: 10px"> {{ tag.empName }}
                </el-tag>
            </el-form-item>
        </el-form>

        <div class="interspaceH"></div>

        <div class="tip">推送周期及内容</div>
        <div class="interspaceH"></div>
        <span class="spanFont">设置规则后将会通过 括号「众哲鑫提醒」提醒员工发送内容。</span>
        <div class="interspaceH"></div>
        <el-form ref="form" label-width="20px">
            <el-form-item>
                <el-button type="primary" @click="openContentHandle">+ 添加规则</el-button>
            </el-form-item>
            <el-form-item v-for="(item, index) in pushContentList" :key="index">
                <div style="display:flex;justify-content: space-between">
                    <div><i class="el-icon-s-management"></i>{{ item.alertMessage }}</div>
                    <div>
                        <el-button type="text" icon="el-icon-edit"
                                   @click="editContentHandle(item, index)"></el-button>
                        <el-button type="text" icon="el-icon-delete"
                                   @click="pushContentList.splice(pushContentList.indexOf(index), 1)"></el-button>
                    </div>
                </div>
                <div v-if="item.alertTimeType == '1'">客户添加企业员工后，{{ item.sendTimeField1 }} 小时 {{ item.sendTimeField2 }}
                    分钟后提醒发送（{{ item.alertMessage }}）
                </div>
                <div v-if="item.alertTimeType == '2'">客户添加企业员工后，{{ item.sendTimeField3 }} 天 {{ item.sendTimeField4 }}
                    后提醒发送（{{ item.alertMessage }}）
                </div>
                <div style="border-radius: 5px; padding: 10px;background-color: #f1f5f7">
                    <div style="border-radius: 5px; padding: 5px;margin-bottom: 10px;background-color: #FFFFFF"
                         v-for="(item1, index1) in item.contentList" :key="index1">
                        <img v-if="item1.imageUrl" :src="item1.imageUrl" class="avatar">
                        <div v-else>{{ item1.content }}</div>
                    </div>
                    <div>共{{ item.contentList.length }}条</div>
                </div>
            </el-form-item>
        </el-form>

        <el-dialog :title="submitType == 'add' ? '添加规则' : '修改规则'" :visible.sync="addRuleVisible" width="60%"
                   :close-on-click-modal="false" :destroy-on-close="true">
            <el-form ref="form" :model="ruleFormContent" label-width="120px">
                <el-form-item label="设置内容名称">
                    <el-input v-model="ruleFormContent.alertMessage"></el-input>
                </el-form-item>
                <el-form-item label="设置发送时间">
                    <el-radio v-model="ruleFormContent.alertTimeType" label="1"
                              style="display: flex;align-items: center;">
                        <div style="display: flex; align-items: center;align-content: center">
                            <div style="margin: 0 10px">客户添加企业员工后，</div>
                            <el-input v-model="ruleFormContent.sendTimeField1" style="width: 150px"
                                      :disabled="ruleFormContent.alertTimeType != '1'"></el-input>
                            <div style="margin: 0 10px">小时，</div>
                            <el-input v-model="ruleFormContent.sendTimeField2" style="width: 150px"
                                      :disabled="ruleFormContent.alertTimeType != '1'"></el-input>
                            <div style="margin: 0 10px">分钟后提醒发送</div>
                        </div>
                    </el-radio>
                    <el-radio v-model="ruleFormContent.alertTimeType" label="2"
                              style="display: flex;align-items: center;margin-top: 20px">
                        <div style="display: flex; align-items: center;align-content: center">
                            <div style="margin: 0 10px">客户添加企业员工后，</div>
                            <el-input v-model="ruleFormContent.sendTimeField3" style="width: 150px"
                                      :disabled="ruleFormContent.alertTimeType != '2'"></el-input>
                            <div style="margin: 0 10px">天后，</div>
                            <el-time-picker style="width: 150px" v-model="ruleFormContent.sendTimeField4"  value-format="HH:mm:ss"
                                            :disabled="ruleFormContent.alertTimeType != '2'"></el-time-picker>
                            <div style="margin: 0 10px">提醒发送</div>
                        </div>
                    </el-radio>

                </el-form-item>

                <el-form-item label="设置发送内容">
                </el-form-item>

                <TypeContentText ref="contentText" style="width: 80%" :contentList="contentList" type="sop"/>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="addRuleVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitContentHandle">确 定</el-button>
            </span>
        </el-dialog>

        <div class="button-strip">
            <el-button type="primary" @click="submitHandle">设置</el-button>
            <el-divider direction="vertical" content-position="center"></el-divider>
            <el-button plain @click="back">返回</el-button>
        </div>

        <el-dialog title="选择成员" :visible.sync="selectMemberVisible" width="60%" :close-on-click-modal="false"
                   :destroy-on-close="true">
            <List_multiple_select ref="selectMember" :listFields="listFields" :dataSource="memberList" type="filter"/>
            <span slot="footer" class="dialog-footer">
                <el-button @click="selectMemberVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitMember">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import List_multiple_select from "@/components/list_multiple_select/list_multiple_select";
import TypeContentText from "@/components/type_content_text/type_content_text"

const ruleFormContent = {
    alertMessage: '',
    alertTimeType: '1',
    sendTimeField1: '',
    sendTimeField2: '',
    sendTimeField3: '',
    sendTimeField4: '',
}

const initContentList = [{
    contentType: 1,
    content: '',
    imageUrl: '',
    linkContent: {
        linkAddress: '',
        linkTitle: '',
        content: ''
    }
}]

function formatDuring(millisecond) {
    let days = parseInt(millisecond / (1000 * 60 * 60 * 24));
    let hours = parseInt((millisecond % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    let minutes = parseInt((millisecond % (1000 * 60 * 60)) / (1000 * 60));
    let seconds = (millisecond % (1000 * 60)) / 1000;

    return {days, hours, minutes, seconds}
}

export default {
    name: "sop_add",
    components: {List_multiple_select, TypeContentText},
    props: {
        sopData: {
            type: Object,
            default: () => {}
        },
        creatType: {
            type: String,
            default: ""
        },
    },
    data() {
        return {
            addRuleVisible: false,
            selectMemberVisible: false,
            memberList: [],
            listFields: {
                deptName: '所属部门',
                empName: '员工名称'
            },
            ruleForm: {
                sopName: '',
                sopType: '1',
                sopStatus: "true",
                members: []
            },
            submitType: '',
            editIndex: 0,
            ruleFormContent: {...ruleFormContent},
            pushContent: {},
            contentList: [...initContentList],
            pushContentList: []
        }
    },
    watch: {
        sopData(n, o) {
            this.ruleForm['sopName'] = n.sopName
            this.ruleForm['members'] = n.empList

            let pushMessage = JSON.parse(n.pushMessage)
            let messageList = []

            pushMessage.map((item) => {
                let data = {}
                let contentList = []

                data['alertMessage'] = item.alertMessage
                data['alertTimeType'] = item.alertTimeType

                let alertTime = formatDuring(item.alertTime)

                if (item.alertTimeType == '1') {
                    data['sendTimeField1'] = (alertTime.days * 24) + alertTime.hours
                    data['sendTimeField2'] = alertTime.minutes
                } else if (item.alertTimeType == '2') {
                    data['sendTimeField3'] = alertTime.days
                    data['sendTimeField4'] = (alertTime.hours.toString().length == 1 ? 0 + alertTime.hours.toString() : alertTime.hours) + ":" + (alertTime.minutes.toString().length == 1 ? 0 + alertTime.minutes.toString() : alertTime.minutes) + ":" + (alertTime.seconds.toString().length == 1 ? 0 + alertTime.seconds.toString() : alertTime.seconds)
                }

                item.pushMessage.map((item1) => {
                    if (item1.pushType == 1) {
                        contentList.push({
                            contentType: 1,
                            content: item1.pushMessage,
                            imageUrl: '',
                            linkContent: {
                                linkAddress: '',
                                linkTitle: '',
                                content: ''
                            }
                        })
                    } else if (item1.pushType == 2 || item1.pushMessage == 3) {
                        contentList.push({
                            contentType: item1.pushType,
                            content: "",
                            imageUrl: item1.pushMessage,
                            linkContent: {
                                linkAddress: '',
                                linkTitle: '',
                                content: ''
                            }
                        })
                    }
                })

                data['contentList'] = contentList

                messageList.push(data)
            })

            this.pushContentList = messageList
        }
    },
    mounted() {
        this.queryMemberHandle()
    },
    methods: {
        back() {
            this.$emit("currentHandle", "list")
        },
        queryMemberHandle() {
            this.$request("/api/emp/getAllEmp/1_0", {}, "POST").then((data) => {
                this.memberList = data.rows
            })
        },
        closeTagHandle(tag) {
            this.ruleForm.members.splice(this.ruleForm.members.indexOf(tag), 1);
        },
        submitMember() {
            let data = this.$refs.selectMember.getData();
            this.ruleForm.members = data
            this.selectMemberVisible = false
        },
        openContentHandle() {
            this.ruleFormContent = {...ruleFormContent}
            this.contentList = [...initContentList]
            this.submitType = 'add'
            this.addRuleVisible = true
        },
        editContentHandle(data, index) {
            this.ruleFormContent = {...data};
            this.editIndex = index;
            this.submitType = 'edit';
            this.addRuleVisible = true;
            let json = JSON.stringify(data.contentList)
            this.$nextTick(() => {
                this.contentList = JSON.parse(json)
            })
        },
        submitContentHandle() {
            let pushContent = {...this.ruleFormContent}
            pushContent['contentList'] = this.$refs.contentText.getData()
            if (this.submitType == 'add') {
                this.pushContentList.push(pushContent)
            } else {
                this.pushContentList[this.editIndex] = pushContent
            }

            this.$refs.contentText.initData()
            this.addRuleVisible = false
        },
        submitHandle() {
            let me = this
            me.$refs.sopForm.validate((valid) => {
                if (!valid) {
                    return false;
                }

                let form = {...me.ruleForm}

                if (form['members'] == null || form['members'].length == 0) {
                    me.$message.error("未选择企业成员")
                    return
                }

                let pushContentList = [...me.pushContentList]

                let pushMessageList = []

                pushContentList.map((item) => {
                    let alertTime = 0;

                    if (item.alertTimeType == '1') {
                        alertTime = (item.sendTimeField1 * 60 * 60 * 1000) + (item.sendTimeField2 * 60 * 1000)
                    } else if (item.alertTimeType == '2') {
                        let time = 0;
                        if (typeof (item.sendTimeField4) == "string") {
                            time = me.$moment(me.$moment().format("YYYY-MM-DD") + " " + item.sendTimeField4).unix() * 1000
                        } else {
                            time = me.$moment(item.sendTimeField4).valueOf()
                        }
                        alertTime = (item.sendTimeField3 * 24 * 60 * 60 * 1000) + (time - parseInt(me.$moment().startOf('day').format('x')))
                    } else {
                        me.$message.error("未选择提醒时间")
                        return
                    }

                    let pushMessage = []

                    item.contentList.map((item1) => {
                        pushMessage.push({
                            pushType: item1.contentType,
                            pushMessage: item1.imageUrl != null && item1.imageUrl != "" ? item1.imageUrl : item1.content
                        })
                    })

                    pushMessageList.push({
                        alertTime,
                        alertTimeType: item.alertTimeType,
                        alertMessage: item.alertMessage,
                        pushMessage
                    })
                })

                let empArr = []

                form['members'].map((data) => {
                    empArr.push(data.empId)
                })

                form['relationId'] = empArr.toString()
                form['creator'] = "管理员"
                form['pushMessage'] = JSON.stringify(pushMessageList)

                delete form['members']

                let url = "/api/sop/addSop/1_0"
                if (this.creatType == 'edit') {
                    url = "/api/sop/updateSop/1_0"
                    form['sopId'] = me.sopData.sopId
                }

                me.$request(url, form, "POST").then((data) => {
                    if (this.creatType == 'edit') {
                        me.$message.success("修改成功")
                    } else {
                        me.$message.success("添加成功")
                    }
                    me.back()
                })
            })
        }
    }
}
</script>

<style scoped>
.el-divider--vertical {
    height: 2em;
}
</style>
